import isObject from 'lodash/isObject';
import defaultSettings from '@/defaultSettings';
import { getViewMode, setItem, getItem } from '@/utils/utils';

function updateLocalSetting(userId, key, value) {
  let settings = getItem(`user${userId}:settings`, 'localStorage');
  if (isObject(settings)) {
    settings[key] = value;
  } else {
    settings = {
      [key]: value,
    };
  }
  setItem(`user${userId}:settings`, settings, 'localStorage');
}

export default {
  namespace: 'setting',

  state: {
    viewMode: getViewMode(), // 可选值 "normal | inner"; normal表示有header和tab-nav; inner相反
    size: {
      width: '100%',
      height: '100%', // 内容高度(不包括#layout-header、.layout-tabs-nav和.ant-tabs-tabpane的上下内边距)
      fullWidth: '100%',
      fullHeight: '100%', // window高度
    },
    ...defaultSettings,
  },

  effects: {
    *showLeftMenu({ payload }, { put, select }) {
      const userId = yield select(state => state.login.user.userInfo.userId);
      // 记录用户的偏好设置

      updateLocalSetting(userId, 'showLeftMenu', payload);
      yield put({
        type: 'updateSettings',
        payload: { showLeftMenu: payload },
      });
    },
    *expandLeftMenu({ payload }, { put, select }) {
      const userId = yield select(state => state.login.user.userInfo.userId);
      // 记录用户的偏好设置
      updateLocalSetting(userId, 'menuDrawerActive', payload);
      yield put({
        type: 'updateSettings',
        payload: { menuDrawerActive: payload },
      });
    },
    *gutter({ payload }, { put, select }) {
      const userId = yield select(state => state.login.user.userInfo.userId);
      // 记录用户的偏好设置
      updateLocalSetting(userId, 'gutter', payload);
      yield put({
        type: 'updateSettings',
        payload: { gutter: payload },
      });
    },
  },

  reducers: {
    readUserLocalSettings(state, { payload }) {
      return {
        ...state,
        ...getItem(`user${payload}:settings`, 'localStorage'),
      };
    },
    toggleSettingDrawer(state, { payload }) {
      if (payload === true) {
        document.querySelector('body').classList.add('noScroll');
      } else {
        document.querySelector('body').classList.remove('noScroll');
      }
      return {
        ...state,
        settingDrawerActive: payload,
      };
    },
    toggleMenuDrawer(state, { payload }) {
      return {
        ...state,
        menuDrawerActive: payload,
      };
    },
    saveSize(state, { payload }) {
      return {
        ...state,
        size: payload,
      };
    },
    updateSettings(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateViewMode(state, { payload }) {
      // 视图模式变化后，内容高度随之变化，所以需要触发basicLayout中的resize监听，让它重新计算一下高度
      const event = document.createEvent('HTMLEvents');
      event.initEvent('resize', true, false);
      window.dispatchEvent(event);
      return {
        ...state,
        ...payload,
      };
    },
  },
};
